import { AStar } from "./findpath/AStar";
import { GridMap } from "./findpath/Grid";
import { AstarNode } from "./findpath/Node";
import Unit from "./Unit";

export default class MoveComponent {
    public unit: Unit;
    public speed: number;

    public aimNode: AstarNode;
    public nowPos: cc.Vec2;
    private path: AstarNode[];
    private duration: number;
    private nowTime: number;
    private distance:number;
    private callback:Function;
    constructor(unit: Unit) {
        this.unit = unit;
        this.nowPos = unit.pos;
        this.path = [];
        unit.moveComponent = this;
        this.speed = unit.getProperty('moving_speed');
    }
    public update(dt: number) {
        if (this.path.length <= 0) {
            return;
        }
        this.nowTime += dt;
        if (this.nowTime >= this.duration) {
            this.unit.pos = this.aimNode.position;
            this.next();
        } else {
            //this.unit.pos = this.unit.pos.lerp(this.aimNode.position,dt/this.duration);
            this.unit.pos = this.unit.pos.add(this.unit.direction.normalize().mul(dt* this.speed));
        }
    }
    public canelMove(){
        this.path.length = 0;
    }
    public move(x:number, y:number,callback?) {
        this.nowTime = 0;
        this.nowPos = cc.v2(Math.round(this.unit.pos.x), Math.round(this.unit.pos.y));
        this.path = AStar.instance.findPath(this.nowPos, cc.v2(x, y));
        if (callback) {
            this.callback = callback;
        }
        if (!this.path) {
            return;
        }
        this.path.shift();
        
        this.aimNode = this.path.shift();
        if (this.aimNode) {
            this.unit.direction = this.aimNode.position.sub(this.nowPos);
            this.distance = this.unit.direction.len();
            
            this.duration = this.distance / this.speed;
            //this.unit.fsm.changeState('walk');
        }
    }
    private check(unit: Unit): boolean {
        if (unit.isDeath()) {
            return false;
        }
        return GridMap.instance.getNode(Math.round(unit.pos.x), Math.round(this.unit.pos.y)) == this.aimNode;
    }
    private next() {
        
        this.nowTime = 0;
        this.nowPos = this.aimNode.position;
        this.aimNode = this.path.shift();
       
        if (this.aimNode) {
            this.unit.direction = this.aimNode.position.sub(this.nowPos);
            this.distance = this.unit.direction.len();
            this.duration = this.distance / this.speed;
            return;
        }
        // let world = this.unit.world;
        // if (world.checkAllUnit(this.check.bind(this))) {
        //     this.path = AStar.instance.findPath(this.nowPos, cc.v2(this.aimNode.x, this.aimNode.y));
        //     this.path.shift();
        //     this.aimNode = this.path.shift();
        // } else {
           
        // }
    }
}